package cn.tedu._03vehicle.base.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class RateLimitInterceptor implements HandlerInterceptor {
    private static final int MAX_COUNT = 3;
    private static final int WINDOW_SIZE_SECONDS = 60;
    private final ConcurrentHashMap<String, Integer> clientCounts = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, LocalDateTime> lastVisitTimes = new ConcurrentHashMap<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String clientId = request.getRemoteAddr();
        LocalDateTime lastVisitTime=lastVisitTimes.get(clientId);
        if(lastVisitTime==null || LocalDateTime.now().isAfter(lastVisitTime.plusSeconds(WINDOW_SIZE_SECONDS))){
            clientCounts.put(clientId,0);
            lastVisitTimes.put(clientId,LocalDateTime.now());
        }
        int count = clientCounts.merge(clientId,1,Integer::sum);
        if (count>MAX_COUNT){
            throw new RuntimeException("访问过于频繁，请稍后再试");
        }
        return true;
    }
}
